import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm, Radio, Space } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './components/Form';

import * as c from '@/services/consts';
import * as api from '@/services/serviceSet';
import { PageContainer } from '@ant-design/pro-components';

const ServiceSetList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.ServiceSetModel | undefined>(
    undefined,
  );

  const [productId, setProductId] = useState<string | undefined>(undefined);
  const [filterPurchaseChannel, setFilterPurchaseChannel] = useState<
    string | undefined
  >(undefined);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductMenuItems } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductMenuItems: model.getProductMenuItems,
    }),
  );

  const productMenuItems = getProductMenuItems(true);

  const handleFormSubmit = async (record: API.ServiceSetModel) => {
    let result: API.Result;
    if (current) {
      let setModel = {
        ...current,
        ...record,
      };

      setModel.title = record.title;
      setModel.subTitle = record.subTitle;
      setModel.introduce = record.introduce;
      setModel.orgPrice = record.orgPrice;
      setModel.price = record.price;

      result = await api.update(setModel);
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.ServiceSetModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: true,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '渠道',
      width: 160,
      align: 'center',
      dataIndex: 'channel',
      sorter: true,
      renderText: (_, record) => {
        return `${c.getPurchaseChannelText(record.channel)}`;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '类型',
      width: 160,
      align: 'center',
      dataIndex: 'serviceTypeId',
      sorter: true,
      renderText: (_, record) => {
        return `${record.serviceTypeName}(${c.getMemberLevelText(
          record.serviceTypeMemberLevel,
        )})`;
      },
    },
    {
      title: '授权天数',
      align: 'center',
      width: 120,
      dataIndex: 'licenseDays',
      sorter: true,
    },
    {
      title: '标题',
      dataIndex: 'title',
      sorter: true,
    },
    {
      title: '副标题',
      dataIndex: 'subTitle',
      sorter: true,
    },
    {
      title: '价格',
      dataIndex: 'price',
      sorter: true,
    },
    {
      title: '渠道商品ID',
      dataIndex: 'channelItemId',
      sorter: true,
    },
    {
      title: '排序',
      align: 'center',
      width: 80,
      dataIndex: 'sort',
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('serviceset_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('serviceset_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              //console.log('tabKey', tabKey);
              setProductId(tabKey as string);
            },
          },
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          toolbarDoms.push(
            <Space>
              <b>渠道</b>
              <Radio.Group defaultValue="" buttonStyle="solid">
                <Radio.Button
                  value=""
                  onClick={() => {
                    setFilterPurchaseChannel(undefined);
                  }}
                >
                  全部
                </Radio.Button>
                {c.PurchaseChannelSetOptions.map((item) => (
                  <Radio.Button
                    value={item.value}
                    onClick={() => {
                      setFilterPurchaseChannel(item.value);
                    }}
                  >
                    {item.label}
                  </Radio.Button>
                ))}
              </Radio.Group>
            </Space>,
          );
          if (hasRight('serviceset_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ]);
          }

          return toolbarDoms;
        }}
        columns={columns}
        params={{
          productId:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
          channel: filterPurchaseChannel,
        }}
        request={api.list}
      />
      <Form
        visible={formVisible}
        defaultProductId={
          productId && productId !== c.DefaultOptionAll.key
            ? parseInt(productId)
            : undefined
        }
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default ServiceSetList;
